package com.wxxymaker.edu.controller.api;

import com.blade.ioc.annotation.Inject;
import com.blade.mvc.annotation.Param;
import com.blade.mvc.annotation.Path;
import com.blade.mvc.annotation.PathParam;
import com.blade.mvc.annotation.PostRoute;
import com.blade.mvc.ui.RestResponse;
import com.wxxymaker.edu.model.entity.Ask;
import com.wxxymaker.edu.model.entity.AskResult;
import com.wxxymaker.edu.roles.CourseLearnRoles;
import com.wxxymaker.edu.roles.StudentRoles;
import com.wxxymaker.edu.service.AskResultService;
import com.wxxymaker.edu.service.AskService;
import com.wxxymaker.edu.utils.TimeUtils;
import com.wxxymaker.edu.utils.TokenUtils;
import io.github.biezhi.anima.page.Page;

/**
 * @author zyx
 * @date 2018/10/14 - 10:59
 */
@StudentRoles
@CourseLearnRoles
@Path(value = "/course/ask/api", restful = true)
public class AskResultHandlerApi {

    @Inject
    private AskResultService    askResultService;

    @Inject
    private AskService          askService;


    @PostRoute("/:kid/:wid/getAllAskResult")
    public RestResponse getAllAskResult(@PathParam                  Integer kid,
                                        @PathParam                  Integer wid,
                                        @Param(defaultValue = "1")  Integer page,
                                        @Param(defaultValue = "8")  Integer size) {
        Page<AskResult> askResultPage = askResultService.getAskResultByWid(wid, page, size);
        if (askResultPage.getTotalRows() > 0) {
            return RestResponse.ok(askResultPage);
        }
        return RestResponse.fail();
    }

    @PostRoute("/:kid/:wid/publishAskResult")
    public RestResponse publishAskResult(@PathParam Integer     kid,
                                         @PathParam Integer     wid,
                                         @Param     AskResult   askResult) {
        askResult.setTime(TimeUtils.getTime());
        askResult.setAskId(wid);
        askResult.setFromUserId(TokenUtils.currentUser().getId());
        setResults(wid);
        AskResult result = askResultService.add(askResult);
        AskResult resultById = askResultService.getAskResultById(result.getId());
        if (result != null) {
            return  RestResponse.ok(resultById);
        }
        return RestResponse.fail();
    }

    private Integer setResults(Integer wid) {
        Page<Ask> askPage = askService.getAskById(wid);
        Ask ask = askPage.getRows().get(0);
        Integer i = askService.updateByWidResults(ask.getId(), ask.getResults());
        if(i > 0) {
            return 1;
        }
        return 0;
    }

}
